package com.code.leetcode.before50;

/**
 * @author codeDorado
 * @version 1.0
 * @date 2020/7/20 12:04
 * 两数相除，不准用 乘法，除法，取模，如果超出界限就返回 Integer.MAX_VALUE
 */
public class The29 {
    public int divide(int dividend, int divisor) {
        if (divisor == 1) return dividend;
        if (dividend == 0) return 0;
        if (divisor == -1) {
            return dividend > Integer.MIN_VALUE ? -dividend : Integer.MAX_VALUE;
        }

        long a = dividend;
        long b = divisor;
        int sign = 1;
        if ((a > 0 && b < 0) || (a < 0 && b > 0)) sign = -1;
        a = a > 0 ? a : -a;
        b = b > 0 ? b : -b;
        long count = div(a, b);
        if (sign > 0) return count > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) count;
        return - (int) count;
    }

    public long div(long a, long b) {
        if (a < b) return 0;
        long count = 1;
        long tb = b;
        while((tb + tb) < a) {
            count += count;
            tb += tb;
        }
        return count + div(a - tb, b);
    }
}
